const {
    createCollect,
    updateCollect,
    removeCollect,
    restoreCollect,
    findCollect,
    findCollectInfo,
} = require('../service/collect.service')

const {sucOperation} = require("../constant/success.type");
const {failOperation} = require("../constant/err.type");

class CollectController {
    async create(ctx, next) {
        try {
            const { createdAt, updatedAt, ...res } = await createCollect(
                {...ctx.request.body,user_id:ctx.state.user.id}
            );
            ctx.body = {
                ...sucOperation,
                result: res,
            };
        } catch (err) {
            return ctx.body = {
                ...failOperation
            };
        }
    }

    async update(ctx) {
        try {
            const res = await updateCollect(ctx.params.id, ctx.request.body);
            if (res) {
                ctx.body = {
                    ...sucOperation,
                    result: res,
                };
            } else {
                return ctx.body = {
                    ...failOperation
                };
            }
        } catch (err) {
            console.error(err);
        }
    }

    async remove(ctx) {
        const res = await removeCollect(ctx.params.id);

        if (res) {
            ctx.body = {
                ...sucOperation,
            };
        } else {
            return ctx.body = {
                ...failOperation
            };
        }
    }

    async restore(ctx) {
        const res = await restoreGoods(ctx.params.id);
        if (res) {
            ctx.body = {
                ...sucOperation,
            };
        } else {
            return ctx.body = {
                ...failOperation
            };
        }
    }

    async findAll(ctx) {
        const {
            pageNum = 1,
            pageSize = 10,
        } = ctx.request.body;
        // 2. 调用数据处理的相关方法
        const res = await findCollect({ pageNum, pageSize ,user_id:ctx.state.user.id,...ctx.request.body});
        // 3. 返回结果
        ctx.body = {
            ...sucOperation,
            result: res,
        };
    }

    async findOne(ctx) {
        const { id } = ctx.params;
        const result = await findCollectInfo(id);
        if (result) {
            ctx.body = {
                ...sucOperation,
                result,
            };
        } else {
            ctx.body = {
                code: 500,
                message: "id有误",
            };
        }
    }
}

module.exports = new CollectController()
